import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_oldman_health/api/auth_service.dart';
import 'package:flutter_oldman_health/models/response_data_model.dart';
import 'package:flutter_oldman_health/utils/utils.dart';
import 'package:flutter_oldman_health/widget/common_container.dart';

class BindPhonePage extends StatefulWidget {
  @override
  _BindPhoneState createState() {
    return _BindPhoneState();
  }
}

class _BindPhoneState extends State<BindPhonePage> {
  final TextEditingController _controllerOldPhone = TextEditingController();
  final TextEditingController _controllerNewPhone = TextEditingController();
  final TextEditingController _controllerOldVCode = TextEditingController();
  final TextEditingController _controllerNewVCode = TextEditingController();

  String getOldVCodeButton = "获取旧号码验证码";
  String getNewVCodeButton = "获取新号码验证码";
  Color normalColor = Color(0xff41BAB0);
  Color activeColor = Color(0xFFEEEEEE);
  bool waitingOldVCode = false;
  bool waitingNewVCode = false;

  int countdownTimeOld = 0;
  int countdownTimeNew = 0;
  Timer _timer;
  Timer _timerNew;

  void getUserPhone() {
    Utils.getStrSharePreferences("phone").then((value) {
      if (null != value && value.length > 0) {
        setState(() {
          _controllerOldPhone.text = value;
        });
      }
    });
  }
  @override
  void dispose() {
    super.dispose();
    if (_timer != null) {
      _timer.cancel();
    }
    if (_timerNew != null) {
      _timerNew.cancel();
    }
  }

  //(isOld ? getOldVCodeButton : getNewVCodeButton),
  //                   (isOld ? countdownTimeOld : countdownTimeNew),
  //                   (isOld ? waitingOldVCode : waitingNewVCode),
  //                   (isOld ? _timer : _timerNew)
  startCountdown(bool old) {
    if (old) {
      countdownTimeOld = 59;
    } else {
      countdownTimeNew = 59;
    }
    final call = (timer) {
      // print("old $old timer${timer==_timer}");
      setState(() {
        if (old) {
          if (countdownTimeOld < 1) {
            timer.cancel();
            waitingOldVCode = false;
            getOldVCodeButton = "获取验证码";
          } else {
            countdownTimeOld -= 1;
            getOldVCodeButton = "${countdownTimeOld}s后重新获得";
          }
        } else {
          if (countdownTimeNew < 1) {
            timer.cancel();
            waitingNewVCode = false;
            getNewVCodeButton = "获取验证码";
          } else {
            countdownTimeNew -= 1;
            getNewVCodeButton = "${countdownTimeNew}s后重新获得";
          }
        }
      });
    };
    if (old) {
      _timer = Timer.periodic(Duration(seconds: 1), call);
    } else {
      _timerNew = Timer.periodic(Duration(seconds: 1), call);
    }
  }
  @override
  void initState() {
    super.initState();
    getUserPhone();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
            color: Colors.white,
            child: Column(
              // verticalDirection:VerticalDirection.down,
              // mainAxisAlignment: MainAxisAlignment.start,
              // crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                _getTitle(),
                CommonContainer(Row(children: [
                  Text("旧手机号:  ", style: TextStyle(fontSize: 18)),
                  Expanded(
                      flex: 1,
                      child: TextField(
                          keyboardType: TextInputType.number,
                          controller: _controllerOldPhone,
                          maxLines: 1,
                          readOnly: true,
                          inputFormatters: [
                            LengthLimitingTextInputFormatter(11),
                            FilteringTextInputFormatter.digitsOnly
                          ],
                          autofocus: true,
                          style: TextStyle(
                              fontSize: 18,
                              color: Colors.black87,
                              fontWeight: FontWeight.w300),
                          // obscureText: true,
                          decoration: getInputDecoration("请输入旧手机号")))
                ])),
                Row(
                  children: [
                    Expanded(
                        flex: 1,
                        child: CommonContainer(
                            TextField(
                                controller: _controllerOldVCode,
                                maxLines: 1,
                                autofocus: true,
                                inputFormatters: [
                                  LengthLimitingTextInputFormatter(4),
                                  FilteringTextInputFormatter.digitsOnly
                                ],
                                style: TextStyle(
                                    fontSize: 18,
                                    color: Colors.black87,
                                    fontWeight: FontWeight.w300),
                                // obscureText: true,
                                decoration: getInputDecoration("请输入验证码")),
                            margin: EdgeInsets.fromLTRB(20, 0, 10, 0))),
                    CommonContainer(
                        getVCodeWidget(
                            _controllerOldPhone, getOldVCodeButton, true),
                        // _timer, waitingOldVCode, countdownTimeOld),
                        margin: EdgeInsets.only(right: 20),
                        padding: EdgeInsets.all(16))
                  ],
                ),
                CommonContainer(
                    Row(children: [
                      Text("新手机号:  ", style: TextStyle(fontSize: 18)),
                      Expanded(
                          flex: 1,
                          child: TextField(
                              keyboardType: TextInputType.number,
                              controller: _controllerNewPhone,
                              maxLines: 1,
                              autofocus: true,
                              inputFormatters: [
                                LengthLimitingTextInputFormatter(11),
                                FilteringTextInputFormatter.digitsOnly
                              ],
                              style: TextStyle(
                                  fontSize: 18,
                                  color: Colors.black87,
                                  fontWeight: FontWeight.w300),
                              // obscureText: true,
                              decoration: getInputDecoration("请输入新手机号")))
                    ]),
                    margin: EdgeInsets.fromLTRB(20, 40, 20, 20)),
                Row(
                  children: [
                    Expanded(
                        flex: 1,
                        child: CommonContainer(
                            TextField(
                                controller: _controllerNewVCode,
                                maxLines: 1,
                                autofocus: true,
                                inputFormatters: [
                                  LengthLimitingTextInputFormatter(4),
                                  FilteringTextInputFormatter.digitsOnly
                                ],
                                style: TextStyle(
                                    fontSize: 18,
                                    color: Colors.black87,
                                    fontWeight: FontWeight.w300),
                                // obscureText: true,
                                decoration: getInputDecoration("请输入验证码")),
                            margin: EdgeInsets.fromLTRB(20, 0, 10, 0))),
                    CommonContainer(
                        getVCodeWidget(
                            _controllerNewPhone, getNewVCodeButton, false),
                        // getVCodeWidget(_controllerNewPhone, getNewVCodeButton,
                        //     _timerNew, waitingNewVCode, countdownTimeNew),
                        margin: EdgeInsets.only(right: 20),
                        padding: EdgeInsets.all(16))
                  ],
                ),
                Container(
                    margin: EdgeInsets.fromLTRB(20, 40, 20, 0),
                    padding: EdgeInsets.all(16),
                    child: GestureDetector(
                        behavior: HitTestBehavior.translucent,
                        onTap: () async {
                          if (_controllerOldPhone.text == null ||
                              !Utils.phoneStr(_controllerOldPhone.text) ||
                              _controllerOldPhone.text.length != 11) {
                            EasyLoading.showInfo("旧手机号码输入有误");
                            return;
                          }

                          if (_controllerOldVCode.text == null ||
                              _controllerOldVCode.text.length < 4) {
                            EasyLoading.showInfo("请填写验证码");
                            return;
                          }
                          if (_controllerNewPhone.text == null ||
                              !Utils.phoneStr(_controllerNewPhone.text) ||
                              _controllerNewPhone.text.length != 11) {
                            EasyLoading.showInfo("新手机号码输入有误");
                            return;
                          }

                          if (_controllerNewVCode.text == null ||
                              _controllerNewVCode.text.length < 4) {
                            EasyLoading.showInfo("请填写验证码");
                            return;
                          }
                          var response = await AuthService.changeBindPhone(
                              _controllerOldPhone.text,
                              _controllerOldVCode.text,
                              _controllerNewPhone.text,
                              _controllerNewVCode.text);
                          if (response != null && response.statusCode == 200) {
                            ResponseDataModel<String> value1 =
                                ResponseDataModel.fromJson(response.data);
                            if (value1.success()) {
                              EasyLoading.showSuccess('手机号换绑成功');
                              Navigator.pop(context);
                            } else {
                              EasyLoading.showInfo(value1.msg);
                            }
                          }
                        },
                        child: FractionallySizedBox(
                            widthFactor: 1,
                            child: Text("确认",
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 18,
                                    color: Colors.white)))),
                    decoration: BoxDecoration(
                        border: Border.all(color: Color(0xFFEEEEEE), width: 1),
                        color: Color(0xff41BAB0),
                        borderRadius: BorderRadius.all(Radius.circular(58))))
              ],
            )));

    // return
  }

  InputDecoration getInputDecoration(String hintText) {
    return InputDecoration(
        hintText: hintText,
        hintStyle: TextStyle(fontSize: 18),
        //InputBorder.none  OutlineInputBorder()
        border: InputBorder.none);
  }

  Widget _getTitle([String title = "手机号换绑"]) {
    return Container(
        color: Colors.white,
        padding: EdgeInsets.fromLTRB(16, 46, 16, 12),
        child: FractionallySizedBox(
          widthFactor: 1,
          child: Stack(
            alignment: Alignment.center,
            children: [
              Positioned(
                left: 2,
                top: 5,
                child: GestureDetector(
                  behavior: HitTestBehavior.translucent,
                  onTap: () {
                    Navigator.pop(context);
                  },
                  child: Container(
                      child: Icon(Icons.arrow_back_ios),
                      padding: EdgeInsets.fromLTRB(15, 0, 20, 10)),
                ),
              ),
              Text(title,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      fontSize: 22,
                      color: Colors.black87,
                      fontWeight: FontWeight.normal)),
            ],
          ),
        ));
  }

  Widget getVCodeWidget(TextEditingController controllerPhone,
      String getVCodeButton, bool isOld) {
    return GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () async {
          if (controllerPhone.text == null ||
              !Utils.phoneStr(controllerPhone.text) ||
              controllerPhone.text.length != 11) {
            EasyLoading.showInfo("手机号码输入有误");
            return;
          }
          if (!getVCodeButton.contains('验证码')) {
            return;
          }

          var response =
              await AuthService.requestVerificationCode(controllerPhone.text);
          if (response != null && response.statusCode == 200) {
            EasyLoading.showSuccess('获取验证码成功');

            ResponseDataModel<String> value =
                ResponseDataModel<String>.fromJson(response.data);
            if (value.success()) {
              setState(() {
                if (isOld) {
                  waitingOldVCode = true;
                  getOldVCodeButton = "59s后重新获得";
                } else {
                  waitingNewVCode = true;
                  getNewVCodeButton = "59s后重新获得";
                }
              });
              startCountdown(isOld);
            } else {
              EasyLoading.showInfo(value.msg);
            }
          }
        },
        child: Text((isOld ? getOldVCodeButton : getNewVCodeButton),
            style: TextStyle(
                fontSize: 17,
                color: (isOld ? waitingOldVCode : waitingNewVCode)
                    ? activeColor
                    : normalColor)));
  }
}
